// Running RD Regressions and Robustness
clear
eststo clear
// Using Ranking Data
use ../dta/index.dta, clear
keep if abs(running)<=0.5

//Merging on Returns and Industry Codes
merge 1:1 code rd_group using ../dta/daily_returns_rd.dta
merge m:1 code using ../src/industry, nogen keep(match master)

// Old School MCcrary Test
*DCdensity running_opt, breakpoint(0) gen(Xj Yj r0 fhat se_fhat)

// Running Density Test
rddensity running, plot all  genvars(temp) 

// Setting Options for Plot
local aux=round(e(T_q), 0.01)
local text = "Density test t-statistic=`aux'"
local ci_plot_region_l = `"(rarea temp_cil temp_cir temp_grid if temp_group == 0 & abs(temp_grid)<0.8, sort lcolor(white%0) color(red%30))"' ///

local ci_plot_region_r = `"(rarea temp_cil temp_cir temp_grid if temp_group == 1 &  abs(temp_grid)<0.8, sort lcolor(white%0) color(blue%30))"'
local es_plot_line_l = `"(line temp_f temp_grid if temp_group == 0 &  abs(temp_grid)<0.8, sort lcolor(red) lwidth("medthin") lpattern(solid))"'
local es_plot_line_r = `"(line temp_f temp_grid if temp_group == 1 &  abs(temp_grid)<0.8, sort lcolor(blue) lwidth("medthin") lpattern(solid))"'

qui su temp_hist_width if temp_hist_group == 0
local hist_width_l = r(mean)
qui su temp_hist_width if temp_hist_group == 1
local hist_width_r = r(mean)
local plot_histogram_l = `"(bar temp_hist_height temp_hist_center if temp_hist_group == 0 & abs(temp_hist_center)<0.8, barwidth(`hist_width_l') color(red%20))"'
local plot_histogram_r = `"(bar temp_hist_height temp_hist_center if temp_hist_group == 1 & abs(temp_hist_center)<0.8, barwidth(`hist_width_r') color(blue%20))"';
local graph_opt = `"xlabel(-0.5(0.5)0.5) ylabel(0(2)5, nogrid) xline(0, lcolor(black) lwidth(medthin) lpattern(solid)) legend(off) title("") xtitle("Inclusion Index") ytitle("Density") text(3.5 -0.2 "`text'") graphregion(color(white))"'
			

// Plotting Density Test
twoway 	`plot_histogram_l' 	/// 
					`plot_histogram_r' 	/// 
					`ci_plot_region_l' 	///
					`ci_plot_line_l'   	///
					`ci_plot_ebar_l'   	///
					`ci_plot_region_r' 	///
					`ci_plot_line_r'   	///
					`ci_plot_ebar_r'   	///
					`es_plot_line_l' 	///
					`es_plot_point_l' 	///
					`es_plot_line_r' 	///
					`es_plot_point_r' 	///
					,					///
					`graph_opt'
graph export ../gph/density_test.pdf, replace font(palatino)		
